package com.linkhouse.interfaces;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.linkhouse.domain.po.CommentContent;
import com.linkhouse.domain.po.RoomComment;
import com.mongodb.client.result.DeleteResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/*评论操作*/
@RestController
@RequestMapping("comment")
@RefreshScope //开启自动刷新配置
public class CommentInterfaces {

    @Autowired
    private MongoTemplate mongoTemplate;

    /*评论添加*/
    @PostMapping
    public void insertComment(@RequestBody RoomComment roomComment){
        //判断要创建的集合是否存在
        if (!mongoTemplate.collectionExists("tb_comment")){
            /*建表*/
            mongoTemplate.createCollection("tb_comment");
            System.err.println("表创建成功ok");
        }
        List<RoomComment> list = Arrays.asList(roomComment);
        mongoTemplate.insert(list,"tb_comment");
        System.err.println("评论成功");
    }
    /*删除评论*/
    @DeleteMapping("/{id}")
    public void removeComment(@PathVariable("id") String id){
        /*先更具id查询数据*/
        Query query = new Query(Criteria.where("_id").is(id));

        DeleteResult tb_comment = mongoTemplate.remove(query, "tb_comment");
        long deletedCount = tb_comment.getDeletedCount();
        System.out.println(deletedCount>0 ? "删除成功":"删除失败");
    }
    /*回复添加*/
    @PutMapping(value = "{id}")
    public void insertReply(@PathVariable("id") String id,@RequestBody CommentContent commentContent){
        /*先更具id查询数据*/
        Query query = new Query(Criteria.where("_id").is(id));
        List<RoomComment> tb_comment = mongoTemplate.find(query, RoomComment.class, "tb_comment");
        RoomComment queryRoomComment = tb_comment.get(0);
        /*修改的字段和内容*/
        if (StrUtil.isBlank(queryRoomComment.getReply())) {
            List<CommentContent> reply = new ArrayList<>();
            reply.add(commentContent);
            String str = JSONObject.toJSONString(reply);
            queryRoomComment.setReply(str);
        }else {
            String reply = queryRoomComment.getReply();
            List<CommentContent> replyList = JSONObject.parseObject(reply, List.class);
            replyList.add(commentContent);
            queryRoomComment.setReply(JSONObject.toJSONString(replyList));
        }
        Update update = new Update().set("reply",String.valueOf(queryRoomComment.getReply()));
        mongoTemplate.updateFirst(query,update,"tb_comment");
        System.err.println("评论回复成功");
    }
}
